package com.wk.base.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.core.view.isVisible
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textview.MaterialTextView
import com.wk.base.R

/**
 * @author peng
 * @date 2021/1/21
 * Paging 加载更多时候，根据当前状态显示，加载中，加载失败等
 */
class WkLoadStateAdapter(private val retryBlock: (() -> Unit)? = null) : LoadStateAdapter<WkLoadStateAdapter.WkLoadStateHolder>(){
    override fun onBindViewHolder(holder: WkLoadStateHolder, loadState: LoadState) {
        holder.progress.isVisible = loadState is LoadState.Loading
        holder.loadingContent.text = when(loadState){
            is LoadState.Loading->holder.itemView.context.getString(R.string.loading)
            is LoadState.Error->"${holder.itemView.context.getString(R.string.load_error)}${if (retryBlock!=null) "，请点击重试" else ""}"
            is LoadState.NotLoading->holder.itemView.context.getString(R.string.load_divider)
        }
        holder.itemView.setOnClickListener {
            if (loadState is LoadState.Error){
                //加载失败了重试，重试的方法需要传进来
                retryBlock?.invoke()
            }
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        loadState: LoadState
    ): WkLoadStateHolder {
        return WkLoadStateHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_load_state_footer,parent,false))
    }

    class WkLoadStateHolder(itemView:View) : RecyclerView.ViewHolder(itemView){
        val progress = itemView.findViewById<ProgressBar>(R.id.pb_loading)
        val loadingContent = itemView.findViewById<MaterialTextView>(R.id.tv_load_state)
    }
}